package com.gitee.feizns.webtemplate.commons.session.resolver;

import com.gitee.feizns.webtemplate.commons.session.Session;
import com.gitee.feizns.webtemplate.commons.session.SessionManager;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author feizns
 * @since 2019/5/16
 */
public class SessionArgumentResolver implements HandlerMethodArgumentResolver {

    /**
     * 默认的校验请求头
     */
    private static final String DEFAULT_TOKEN_HEADER = "token";

    private String tokenHeader = DEFAULT_TOKEN_HEADER;

    private SessionManager sessionManager;

    public SessionArgumentResolver(SessionManager sessionManager, String tokenHeader) {
        this.tokenHeader = tokenHeader;
        this.sessionManager = sessionManager;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return Session.class.isAssignableFrom(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String token = webRequest.getHeader(tokenHeader);
        return sessionManager.getSession(token);
    }

}
